<template>
  <div class="main-container">
    <!-- 页面标题和货品信息 -->
    <div class="page-header" v-if="currentGoodsInfo.goodsCode">
      <div class="goods-info">
        <h3>{{ currentGoodsInfo.goodsName }} {{ currentGoodsInfo.goodsCode }}</h3>
        <div class="goods-details">
          <span>货品类型：{{ currentGoodsInfo.goodsType || '饮品类' }}</span>
          <span>规格型号：{{ currentGoodsInfo.specs || '20*50*60' }}</span>
          <span>单位：{{ currentGoodsInfo.unit || '瓶' }}</span>
        </div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards" v-if="stats">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-value blue">{{ stats.currentStock || 0 }}</div>
            <div class="stat-label">当前库存</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-value blue">{{ stats.availableStock || 0 }}</div>
            <div class="stat-label">可用库存</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-value orange">{{ stats.pendingOutbound || 0 }}</div>
            <div class="stat-label">待出库</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-value orange">{{ stats.pendingInbound || 0 }}</div>
            <div class="stat-label">待入库</div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button @click="handleExport">导出</el-button>
      <el-button type="primary" @click="handleRefresh">刷新</el-button>
    </div>

    <!-- 库存分布表格 -->
    <div class="table-container">
      <el-table 
        :data="tableData" 
        :loading="loading"
        @selection-change="handleSelectionChange"
        border
        stripe
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" width="80">
          <template #default="{ $index }">
            {{ (pagination.page - 1) * pagination.pageSize + $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="warehouseName" label="仓库名称" />
        <el-table-column prop="locationName" label="仓位名称" />
        <el-table-column prop="currentStock" label="当前库存" />
        <el-table-column prop="availableStock" label="可用库存" />
        <el-table-column prop="pendingInbound" label="待入库" />
        <el-table-column prop="pendingOutbound" label="待出库" />
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup name="kcfb">
import { ref, reactive, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useInventoryQueryApi } from '/@/api/inventory/inventoryQuery'

const route = useRoute()
const api = useInventoryQueryApi()

const loading = ref(false)
const tableData = ref<any[]>([])
const selectedRows = ref<any[]>([])

// 当前货品信息
const currentGoodsInfo = reactive({
  goodsCode: '',
  goodsName: '',
  goodsType: '',
  specs: '',
  unit: '',
  warehouseName: ''
})

// 统计数据
const stats = ref<any>(null)

const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0,
})

// 加载库存分布数据
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      goodsCode: currentGoodsInfo.goodsCode,
      page: pagination.page,
      pageSize: pagination.pageSize,
    }
    
    const res = await api.getStockDistribution(params)
    if (res.data && res.data.result) {
      tableData.value = res.data.result.items || []
      pagination.total = res.data.result.total || 0
    } else {
      tableData.value = []
      pagination.total = 0
    }
  } catch (e) {
    ElMessage.error('加载库存分布数据失败')
  } finally {
    loading.value = false
  }
}

// 加载统计数据
const loadStats = async () => {
  try {
    const res = await api.getStats({
      goodsCode: currentGoodsInfo.goodsCode,
      warehouseName: undefined // 不传仓库名称，查询全部仓库
    })
    if (res.data && res.data.result) {
      stats.value = res.data.result
    }
  } catch (e) {
    console.error('加载统计数据失败:', e)
  }
}

// 刷新
const handleRefresh = () => {
  loadData()
  loadStats()
}

// 导出
const handleExport = async () => {
  try {
    const params = {
      goodsCode: currentGoodsInfo.goodsCode,
      page: 1,
      pageSize: 10000 // 导出所有数据
    }
    const res = await api.exportStockDistribution(params)
    
    // 创建下载链接
    const blob = new Blob([res.data], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `库存分布_${new Date().toISOString().slice(0, 10)}.xlsx`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 表格选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.page = 1
  loadData()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadData()
}

onMounted(async () => {
  // 处理路由参数
  if (route.query.goodsCode) {
    currentGoodsInfo.goodsCode = route.query.goodsCode as string
  }
  if (route.query.goodsName) {
    currentGoodsInfo.goodsName = route.query.goodsName as string
  }
  if (route.query.warehouseName) {
    currentGoodsInfo.warehouseName = route.query.warehouseName as string
  }
  
  await loadData()
  await loadStats()
})
</script>

<style scoped>
.main-container { 
  padding: 20px; 
}

.page-header {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.goods-info h3 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 18px;
}

.goods-details {
  display: flex;
  gap: 20px;
  color: #666;
  font-size: 14px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  padding: 20px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-value.blue {
  color: #409eff;
}

.stat-value.orange {
  color: #e6a23c;
}

.stat-label {
  color: #666;
  font-size: 14px;
}

.action-buttons {
  margin-bottom: 20px;
}

.table-container { 
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination { 
  display: flex; 
  justify-content: flex-end; 
  padding: 12px 0; 
}
</style>
